package com.ww.book.javaconcurrencyinpractice.ch03;

public class SafeThreadStart {
    private int counter = 0;
    private boolean initialized = false;

    public SafeThreadStart() {
        counter = 100;
        // 不要在这里启动线程
    }

    /**
     * 单独的初始化方法，在对象完全构造后调用
     */
    public void initialize() {
        if (!initialized) {
            new Thread(() -> {
                for (int i = 0; i < 100; i++) {
                    increment();
                }
            }).start();
            initialized = true;
        }
    }

    public synchronized void increment() {
        counter++;
    }

    public synchronized int getCounter() {
        return counter;
    }
}
